<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/15 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\components\oss;

use Yii;
use yii\base\BaseObject;

class Oss extends BaseObject
{
    /** @var object 上传处理类 */
    public $handler;

    /**
     * 初始化
     */
    public function init()
    {
        parent::init();
        $handler = Yii::$app->config->getItem('ossHandler');
        $this->handler = Yii::$app->$handler;
        // 配置上传组件
        $this->handler->setConfig(Yii::$app->config->getItem($handler));
    }

    /**
     * 上传文件
     * @param object $file 要上传的文件对象
     * @param int $uid 上传用户ID
     * @param bool $isAvatar 是否是头像
     * @param bool $deleteTempFile 是否删除临时文件.
     * @return mixed
     * @see \yii\web\UploadedFile::getInstance()
     */
    public function upload(&$file, $uid = 0, $isAvatar = false, $deleteTempFile = true)
    {
        $fileName = $this->handler->generateFileName($uid);
        $ext = $file->getExtension();
        $path = $isAvatar ? $this->handler->generateAvatarFilePath($uid) . $fileName . '.' . $ext : $this->handler->generateFilePath($uid) . $fileName . '.' . $ext;
        // 上传
        $res = $this->handler->upload($path, $file, $deleteTempFile);
        $res['data']['fileName'] = $fileName;
        $res['data']['fileExt'] = $ext;

        return $res;
    }

    /**
     * 删除文件
     * @param string $object 要删除的OSS对象文件路径
     * @return mixed
     */
    public function delete($object)
    {
        return $this->handler->delete($object);
    }
}